<template>
  <view class="calendar-mask" v-if="visible" @tap="close">
    <view class="calendar-panel" @tap.stop>
      <!-- 顶部 -->
      <view class="calendar-header">
        <text class="btn-clear" @tap="clear">清空</text>
        <text class="title">用车时间选择</text>
        <text class="btn-close" @tap="close">✕</text>
      </view>

      <!-- 快捷天数 -->
      <view class="quick-days">
        <view v-for="d in quickDays" :key="d"
          :class="['qd', activeDays===d?'qd-active':'']"
          @tap="applyQuickDays(d)">
          {{ d }}天
        </view>
      </view>

      <!-- 月份切换 -->
      <view class="month-bar">
        <text class="arrow" @tap="prevMonth">‹</text>
        <text class="ym">{{ viewYear }}年{{ pad2(viewMonth) }}月</text>
        <text class="arrow" @tap="nextMonth">›</text>
      </view>

      <!-- 星期 -->
      <view class="dow">
        <text v-for="w in ['日','一','二','三','四','五','六']" :key="w">{{ w }}</text>
      </view>

      <!-- 日历 -->
      <view class="grid">
        <view v-for="(d,idx) in monthGrid" :key="idx"
          :class="[
            'day',
            !d.inMonth?'day-dim':'',
            (d.ts>=startTs && d.ts<=endTs)?'day-range':'',
            (d.ts===startTs)?'day-start':'',
            (d.ts===endTs && startTs!==endTs)?'day-end':''
          ]"
          @tap="onPickDay(d)"
        >
          <text v-if="d.inMonth">
            <template v-if="d.ts===startTs">取</template>
            <template v-else-if="d.ts===endTs && startTs!==endTs && d.m===endMonth">还</template>
            <template v-else>{{ d.date }}</template>
          </text>
        </view>
      </view>

      <!-- 时分选择 -->
      <view class="time-pickers">
        <view class="tp-col">
          <view class="tp-title">取车时间</view>
          <picker-view class="picker" indicator-style="height: 40px" :value="startPickerIdx" @change="onStartTimeChange">
            <picker-view-column>
              <view v-for="(h,i) in hours" :key="'sh'+i" class="picker-item">{{ h }}时</view>
            </picker-view-column>
            <picker-view-column>
              <view v-for="(m,i) in minutes" :key="'sm'+i" class="picker-item">{{ m }}分</view>
            </picker-view-column>
          </picker-view>
        </view>
        <view class="tp-col">
          <view class="tp-title">还车时间</view>
          <picker-view class="picker" indicator-style="height: 40px" :value="endPickerIdx" @change="onEndTimeChange">
            <picker-view-column>
              <view v-for="(h,i) in hours" :key="'eh'+i" class="picker-item">{{ h }}时</view>
            </picker-view-column>
            <picker-view-column>
              <view v-for="(m,i) in minutes" :key="'em'+i" class="picker-item">{{ m }}分</view>
            </picker-view-column>
          </picker-view>
        </view>
      </view>

      <!-- 底部 -->
      <view class="preview">
        <view>取车：{{ fmtFull(startDate) }}</view>
        <view>还车：{{ fmtFull(endDate) }}</view>
      </view>

      <button class="ok" @tap="confirm">确定</button>
    </view>
  </view>
</template>

<script>
export default {
  name:"rent-calendar",
  props:{ visible:Boolean, minDays:{type:Number,default:1} },
  data(){
    const today=new Date(); today.setHours(10,0,0,0);
    return {
      quickDays:[7,14,21,30],
      activeDays:7,
      startDate:today,
      endDate:new Date(today.getTime()+6*86400000),

      viewYear:today.getFullYear(),
      viewMonth:today.getMonth()+1,
      monthGrid:[],

      hours:Array.from({length:24},(_,i)=>(''+i).padStart(2,'0')),
      minutes:Array.from({length:60},(_,i)=>(''+i).padStart(2,'0')),
      startPickerIdx:[10,0],
      endPickerIdx:[10,0]
    }
  },
  computed:{
    startTs(){return this.startDate?this.onlyDate(this.startDate).getTime():0;},
    endTs(){return this.endDate?this.onlyDate(this.endDate).getTime():0;},
    endMonth(){return this.endDate?this.endDate.getMonth()+1:null;}
  },
  watch:{
    visible(v){ if(v) this.buildMonthGrid(this.viewYear,this.viewMonth); }
  },
  methods:{
    pad2(n){return (''+n).padStart(2,'0');},
    onlyDate(d){const t=new Date(d);t.setHours(0,0,0,0);return t;},
    fmtFull(d){ if(!d) return '--'; return `${this.pad2(d.getMonth()+1)}月${this.pad2(d.getDate())}日 ${this.pad2(d.getHours())}:${this.pad2(d.getMinutes())}`;},

    buildMonthGrid(y,m){
      const first=new Date(y,m-1,1), fdow=first.getDay();
      const daysInMonth=new Date(y,m,0).getDate();
      const prevDays=new Date(y,m-1,0).getDate();
      const grid=[];
      for(let i=fdow-1;i>=0;i--){
        const dt=new Date(y,m-2,prevDays-i);dt.setHours(0,0,0,0);
        grid.push({inMonth:false,y,m:m-1,date:prevDays-i,ts:dt.getTime()});
      }
      for(let d=1; d<=daysInMonth; d++){
        const dt=new Date(y,m-1,d);dt.setHours(0,0,0,0);
        grid.push({inMonth:true,y,m,date:d,ts:dt.getTime()});
      }
      while(grid.length<42){
        const next=grid.length-(fdow+daysInMonth)+1;
        const dt=new Date(y,m,next);dt.setHours(0,0,0,0);
        grid.push({inMonth:false,y,m:m+1,date:next,ts:dt.getTime()});
      }
      this.monthGrid=grid;
    },
    prevMonth(){let y=this.viewYear,m=this.viewMonth-1;if(m<1){m=12;y--;}this.viewYear=y;this.viewMonth=m;this.buildMonthGrid(y,m);},
    nextMonth(){let y=this.viewYear,m=this.viewMonth+1;if(m>12){m=1;y++;}this.viewYear=y;this.viewMonth=m;this.buildMonthGrid(y,m);},

    applyQuickDays(d){
      this.activeDays=d;
      this.endDate=new Date(this.startDate.getTime()+(d-1)*86400000);
      this.syncPickers();
    },
    onPickDay(d){
      if(!d.inMonth) return;
      const dayDate=new Date(d.ts);
      const today=new Date(); today.setHours(0,0,0,0);
      const min=new Date(today); min.setDate(min.getDate()+this.minDays-1);
      if(dayDate<min){
        return uni.showToast({title:`最早可选 ${this.minDays===1?'今天':this.minDays+'天后'}`,icon:'none'});
      }
      this.startDate=this.setHM(dayDate,this.startDate.getHours(),this.startDate.getMinutes());
      this.endDate=new Date(this.startDate.getTime()+(this.activeDays-1)*86400000);
      this.syncPickers();
    },
    setHM(d,h,m){const t=new Date(d);t.setHours(h,m,0,0);return t;},
    syncPickers(){
      this.startPickerIdx=[this.startDate.getHours(),this.startDate.getMinutes()];
      this.endPickerIdx=[this.endDate.getHours(),this.endDate.getMinutes()];
    },
    onStartTimeChange(e){
      const [h,m]=e.detail.value;
      this.startDate=this.setHM(this.startDate,h,m);
      if(this.endDate<=this.startDate){
        this.endDate=new Date(this.startDate.getTime());
        this.endPickerIdx=[h,m];
      }
    },
    onEndTimeChange(e){
      const [h,m]=e.detail.value;
      this.endDate=this.setHM(this.endDate,h,m);
      if(this.endDate<=this.startDate){
        this.startDate=new Date(this.endDate.getTime());
        this.startPickerIdx=[h,m];
      }
    },
    clear(){this.startDate=null;this.endDate=null;this.activeDays=7;},
    close(){this.$emit('close');},
    confirm(){
      this.$emit('confirm',{start:this.startDate,end:this.endDate,days:this.activeDays});
      this.close();
    }
  }
}
</script>

<style scoped lang="scss">
.calendar-mask{position:fixed;left:0;top:0;right:0;bottom:0;background:rgba(0,0,0,.5);display:flex;align-items:flex-end;z-index:999;}
.calendar-panel{width:100%;background:#fff;border-top-left-radius:20rpx;border-top-right-radius:20rpx;padding:20rpx;}
.calendar-header{display:flex;justify-content:space-between;align-items:center;padding:10rpx 0;font-size:30rpx;font-weight:600;}
.btn-clear,.btn-close{color:#666;font-size:28rpx;}
.title{font-weight:700;}
.quick-days{display:flex;justify-content:space-around;margin:10rpx 0;}
.qd{padding:10rpx 20rpx;border:1px solid #ccc;border-radius:30rpx;font-size:26rpx;color:#666;}
.qd-active{background:#0075B8;color:#fff;border-color:#0075B8;}
.month-bar{display:flex;justify-content:center;align-items:center;gap:30rpx;margin:10rpx 0;}
.ym{font-weight:700;}
.dow{display:grid;grid-template-columns:repeat(7,1fr);text-align:center;color:#999;margin-bottom:10rpx;}
.grid{display:grid;grid-template-columns:repeat(7,1fr);gap:6rpx;}
.day{position:relative;text-align:center;height:80rpx;line-height:80rpx;border-radius:12rpx;background:#fff;font-size:30rpx;color:#333;}
.day-dim{color:#ccc;background:#f9f9f9;}
.day-range{background:#e6f2ff;}
.day-start,.day-end{background:#0075B8;color:#fff;font-weight:700;}
.time-pickers{display:flex;gap:16rpx;margin-top:10rpx;}
.tp-col{flex:1;}
.tp-title{text-align:center;font-size:28rpx;color:#1f2329;margin-bottom:8rpx;}
.picker{height:200rpx;}
.picker-item{height:40px;display:flex;align-items:center;justify-content:center;font-size:28rpx;}
.preview{display:flex;justify-content:space-between;margin:20rpx 0;color:#333;font-size:28rpx;}
.ok{width:100%;height:80rpx;line-height:80rpx;background:#0075B8;color:#fff;font-size:32rpx;font-weight:700;border-radius:12rpx;}
</style>
